<template>
    <div class="app-container">
      <searchForm 
        :formOptions="formOptions" 
        @onSearch="onSearch" 
        @onReset="onReset"
        v-show="showSearch" />
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-hasPermi="[addBtnPremission]">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-hasPermi="[exportBtnPremission]">
          <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出</el-button>
        </el-col>
        <el-col :span="1.5" v-hasPermi="[importBtnPremission]">
          <el-button
              type="warning"
              plain
              size="mini"
              @click="downloadTemplate"
            >下载导入模板</el-button>
        </el-col>
        <el-col :span="1.5" v-hasPermi="[importBtnPremission]">
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            :headers="uploadHeaders"
            accept=".xlsx"
            :show-file-list="false"
            :on-success="onSuccess"
            :multiple="false"
            >
            <el-button
              type="warning"
              plain
              icon="el-icon-upload2"
              size="mini"
            >导入</el-button>
          </el-upload>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table 
        :data="tablelist" 
        @selection-change="handleSelectionChange"
        row-key="id"
        default-expand-all
        :tree-props="{children: 'childList', hasChildren: 'hasChildren'}"
        >
        <el-table-column label="组织名称" prop="name" :show-overflow-tooltip="true" align="left" />
        <!-- <el-table-column label="组织简称" prop="nickName" align="left" /> -->
        <el-table-column label="组织负责人" prop="headTeaList.userName" :formatter="colorData" align="left"  v-if="isCommittee"/>
        <el-table-column label="组织负责人" prop="headStuList.userName" :formatter="colorStuData" align="left"  v-if="isStudentClub"/>
        <el-table-column label="成立时间" prop="buildTime" align="left" />
        <el-table-column label="组织简介" prop="introduction" align="left" />
        <el-table-column label="组织人数" prop="personCount" align="left" />
        <el-table-column fixed="right" label="操作" align="left" class-name="small-padding fixed-width">
          <template v-if="scope.row.parentId != '0'" slot-scope="scope">
            <el-button size="mini" type="text" v-hasPermi="[editBtnPremission]"  @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" v-hasPermi="[delBtnPremission]"  @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Add ref="addRef" :treeData="tablelist" :isCommittee="isCommittee" :isStudentClub="isStudentClub"  @updateList="getList"></Add>
    </div>
  </template>
  <script>
  var downloadLoadingInstance = null
  import { 
    organizeTree,
    removeOrganize,
    organizeList,
    organizeTemplate,
    studentOrganizeTemplate,
    studentOrganizeList,
    delStudentOrganize,
    exportStudentOrganize
   } from "@/api/leagueManagement/organize";
  import searchForm from "@/components/Search/searchForm.vue";
  import Add from "./moudles/addDlg.vue"
import { Loading } from 'element-ui'
  import errorCode from '@/utils/errorCode'
  import { tansParams, blobValidate, handleTree } from "@/utils/util";
  import { getToken } from "@/utils/auth";
  import { saveAs } from 'file-saver'
  export default {
    components: { 
      searchForm,
      Add
    },
    data() {
      return {
        formOptions: [
           
            {
                label: "组织名称",
                prop: "name",
                element: "el-input",
                placeholder: "请输入组织名称",
            },
        ],
        showSearch: true,
        tablelist: [],
        queryParams: {
          name: ''
        },
        uploadHeaders: { Authorization: "Bearer " + getToken() },
      };
    },
    watch: {
      
    },
    computed: {
      isCommittee() {
        return this.$route.query.type == 'committee'
      },
      isStudentClub() {
        return this.$route.query.type == 'studentClub'
      },
      uploadAction() {
        if (this.$route.query.type == 'committee') {
          return process.env.VUE_APP_BASE_API + '/league/organize/importOrg'
        }
        if (this.$route.query.type == 'studentClub') {
          return process.env.VUE_APP_BASE_API + '/league/union/importUnion'
        }
      },
      addBtnPremission() {
        if(this.isCommittee) {
          return 'tuanCommittee:organization:add'
        }
        if(this.isStudentClub) {
          return 'tuanCommittee:studentClub:add'
        }
      },
      exportBtnPremission() {
        if(this.isCommittee) {
          return 'tuanCommittee:organization:export'
        }
        if(this.isStudentClub) {
          return 'tuanCommittee:studentClub:export'
        }
      },
      importBtnPremission() {
        if(this.isCommittee) {
          return 'tuanCommittee:organization:import'
        }
        if(this.isStudentClub) {
          return 'tuanCommittee:studentClub:import'
        }
      },
      editBtnPremission() {
        if(this.isCommittee) {
          return 'tuanCommittee:organization:edit'
        }
        if(this.isStudentClub) {
          return 'tuanCommittee:studentClub:edit'
        }
      },
      delBtnPremission() {
        if(this.isCommittee) {
          return 'tuanCommittee:organization:del'
        }
        if(this.isStudentClub) {
          return 'tuanCommittee:studentClub:del'
        }
      }
    },
    created() {
      console.log(this.$route, 'this.$route')
      this.getList()
    },
    methods: {
      colorData(row) {
            let colorArr = []; //新建一个数组
            row.headTeaList.forEach((item, index) => { 
            //对当前的颜色数组进行遍历处理
                colorArr.push(item.userName + '; '); //给它们每一项加上分号和空格
            });
            return colorArr; //将有分隔符的颜色数组返回
        },
        colorStuData(row) {
            let colorArr = []; //新建一个数组
            row.headStuList.forEach((item, index) => { 
            //对当前的颜色数组进行遍历处理
                colorArr.push(item.userName + '; '); //给它们每一项加上分号和空格
            });
            return colorArr; //将有分隔符的颜色数组返回
        },
      //文件上传成功
      onSuccess(response) {
        if (response.code == 200) {
          this.$message.success(`导入成功：${response.data.successSize},导入失败：${response.data.errorSize}`);
          if(response.url) {
            window.open(process.env.VUE_APP_BASE_API + response.url);
          }
          this.getList();
        } else {
          this.$message.error(response.msg);
        }
      },
      downloadTemplate() {
        downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
        if (this.isCommittee) {
          organizeTemplate().then(async (data) => {
            const isBlob = blobValidate(data);
            if (isBlob) {
              const blob = new Blob([data],{
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              })
              saveAs(blob, `组织管理导入模版_${new Date().getTime()}.xlsx`)
            } else {
              const resText = await data.text();
              const rspObj = JSON.parse(resText);
              const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
              this.$message.error(errMsg);
            }
            downloadLoadingInstance.close();
          })
        }
        if (this.isStudentClub) {
          studentOrganizeTemplate().then(async (data) => {
            const isBlob = blobValidate(data);
            if (isBlob) {
              const blob = new Blob([data],{
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              })
              saveAs(blob, `学生社团组织导入模版_${new Date().getTime()}.xlsx`)
            } else {
              const resText = await data.text();
              const rspObj = JSON.parse(resText);
              const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
              this.$message.error(errMsg);
            }
            downloadLoadingInstance.close();
          })
        }
      },
      handleAdd (rowdata) {
        // this.$refs.addRef.open()
        this.$refs.addRef.open(rowdata, "add");
      },
      handleSelectionChange(val){
        console.log(val, 'val')
      },
      handleUpdate(rowdata){
        this.$refs.addRef.open(rowdata, "edit")
      },
      handleDelete(rowdata){
        this.$modal
          .confirm(`确认删除"${rowdata.name}"组织吗？`)
          .then(()=> {
            if (this.isCommittee) {
              return removeOrganize(rowdata.id);
            }
            if (this.isStudentClub) {
              return delStudentOrganize(rowdata.id);
            }
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      getList () {
        if (this.isCommittee) {
          organizeTree(this.queryParams).then((res) => {
            if (Array.isArray(res)) {
              this.deleteEmpty(res)
              this.tablelist = res
            }
          })
        }
        if (this.isStudentClub) {
          studentOrganizeList(this.queryParams).then((res) => {
              this.tablelist = handleTree(res.rows, 'id', 'parentId', 'childList')
          })
        }
      },
      deleteEmpty (data) {
        data.forEach(element => {
          if (element.childList) {
            if (element.childList.length > 0) {
              this.deleteEmpty(element.childList)
            } else {
              delete element.childList
            }
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        if (this.isCommittee) {
          this.download(
            "/league/organize/export",
            {
              ...this.queryParams
            },
            `团委组织_${new Date().getTime()}.xlsx`
          );
        }
        if (this.isStudentClub) {
          this.download(
            "/league/union/export",
            {
              ...this.queryParams
            },
            `学生社团组织_${new Date().getTime()}.xlsx`
          );
        }
        
      },
      onSearch(val) {
          // 查询条件和分页数据合并
          const arr = Object.assign(this.queryParams, val);
          this.queryParams.pageNum = 1;
          this.getList();
      },
      // 重置
      onReset(data) {
          this.queryParams.pageNum = 1;
          const arr = Object.assign(this.queryParams, data);
          this.getList();
      },
    }
  };
  </script>
  <style scoped lang="scss">
  .head-container {
    overflow-x: scroll;
  }
  </style>